package cn.fl.ass.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssTrailCarDInfService;
import cn.fl.ass.service.IAssTrailCarDService;
import cn.fl.ass.service.IAssTrailCarFlowInsMcrLngService;
import cn.fl.ass.vo.AssTrailCarDInfVO;
import cn.fl.ass.vo.AssTrailCarDVO;
import cn.fl.capital.condition.CapOverdueInfoQueryCondition;
import cn.fl.capital.service.ICapOverdueInfoService;
import cn.fl.capital.vo.CapOverdueInfoVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.transform.InsApplicationVOTransform;
import cn.fl.insurance.vo.InsApplicationVO;
import cn.fl.mcr.condition.McrBillDQC;
import cn.fl.mcr.condition.McrBillMQC;
import cn.fl.mcr.constant.McrBillMConstant;
import cn.fl.mcr.service.IMcrBillDService;
import cn.fl.mcr.service.IMcrBillMService;
import cn.fl.mcr.vo.McrBillDVO;
import cn.fl.mcr.vo.McrBillMVO;
import fl.ass.facade.api.IAssTrailCarFlowHistoryApi;
import fl.ass.facade.condition.AssTrailCarDQueryCondition;
import fl.ass.facade.condition.AssTrailCarFlowHistoryQC;
import fl.ass.facade.dto.AssTrailCarFlowHistoryDTO;
import ins.car.facade.car.car.api.IInsQueryApiService;
import ins.car.facade.car.car.condition.InsApplicationQC;
import ins.car.facade.car.car.condition.InsPayDetailIns02QC;
import ins.car.facade.car.car.condition.InsPayDetailIns03QC;
import ins.car.facade.car.car.condition.InsPayDetailIns04QC;
import ins.car.facade.car.car.dto.InsApplicationDTO;
import ins.car.facade.car.car.dto.InsPayDetailIns02DTO;
import ins.car.facade.car.car.dto.InsPayDetailIns03DTO;
import ins.car.facade.car.car.dto.InsPayDetailIns04DTO;

/**
 * @Description: 各个流程中展示保险，经营，LNG贷款信息
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssTrailCarFlowInsMcrLngServiceImpl implements IAssTrailCarFlowInsMcrLngService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IAssTrailCarFlowInsMcrLngService.class);
	@Autowired
	private IMcrBillMService  mcrBillMService;
	@Autowired
	private IMcrBillDService mcrBillDService;
    @Autowired
    private ICapOverdueInfoService capOverdueInfoService;
    @Autowired
    private IInsQueryApiService insQueryApiService;
    @Autowired
    private IAssTrailCarFlowHistoryApi assTrailCarFlowHistoryApi;
    
	@Autowired
	private ICstBscInfoService cstBscInfoService;
    
	/**
	 * AssTrailCarDInf 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDInfService assTrailCarDInfService;
	/**
	 * AssTrailCarD 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDService assTrailCarDService;

	@Override
	public List<McrBillMVO> getMcrBillInfo(Long cstId,String loanBziType) throws BaseException {
		McrBillMQC condition=new McrBillMQC();
		//condition.setCstId(Long.parseLong("180125030000598"));
		condition.setCstId(cstId);
		condition.setLoanStsCd(McrBillMConstant.LOAN_STS_CD_4);
		if(StringUtils.isNotEmpty(loanBziType)){
			condition.setLoanBizTypCd(loanBziType);//经营贷款
		}
		List<McrBillMVO> mcrbills=mcrBillMService.searchList(condition);
		List<Long> ids = new ArrayList<Long>();
		if(CollectionUtils.isNotEmpty(mcrbills)){
			for (McrBillMVO vo : mcrbills) {
				ids.add(vo.getId());
			}
		}

		List<CapOverdueInfoVO> capOverdues=null;
		List<McrBillDVO> mcrBillds=null;
		if(ids.size()>0){
			McrBillDQC cn=new McrBillDQC();
			cn.setBillIdList(ids);
			mcrBillds=mcrBillDService.searchList(cn);
			CapOverdueInfoQueryCondition capcon=new CapOverdueInfoQueryCondition();
			capcon.setPaySchIdList(ids);
			capcon.setCstId(cstId);
			capcon.setIsDel(0);
			capcon.setUsrId(CurrentThreadContext.getCurrentUserId());
			capcon.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			capcon.setSysCd(CurrentThreadContext.getCurrentSysCd());
			capcon.setDataStatusCd(BaseConstant.IS_YESNO_NO_STR);
//			capOverdues=capOverdueInfoService.searchOvdPayList(capcon);
			capOverdues=capOverdueInfoService.searchList(capcon);
		}

		for (McrBillMVO mbm : mcrbills) {
			Long totCapAmt=0L;//已还本金合计
			Long totIntrAmt=0L;//已还利息合计
			Long totdefaultAmt=0L;//已还罚息合计
			Long overplusCapAmt=0L; //剩余本金合计
			Long overplusIntrAmt=0L;//剩余利息合计
			Long overplusdefaultAmt=0L;//剩余罚息合计
			Long overdueAmount=0L;//逾期金额:逾期租金总金额
			Long clearAmt=0L;//结清--剩余本金合计+剩余利息合计+应收罚息合计+逾期租金合计
			for (McrBillDVO mbd : mcrBillds) {
				if(mbm.getId().equals(mbd.getBillId())){
                    totCapAmt += mbd.getPaidCapAmt();//已还本金
                    totIntrAmt += mbd.getPaidIntrAmt();//已还利息
                    // 计算还款日从当天往后的本金和利息的合计
                    if (mbd.getPayDt().after(new Date())) {
                        overplusCapAmt += (mbd.getCapAmt());//剩余本金合计
                        overplusIntrAmt += (mbd.getIntrAmt());//剩余利息合计
                    }
				}
			}
			for (CapOverdueInfoVO capvo : capOverdues) {
				if(mbm.getId().equals(capvo.getPaySchId())){
					totdefaultAmt+=capvo.getPayAmount();//payAmount
					overplusdefaultAmt+=(capvo.getPenaltyAmount()-capvo.getPayAmount());
					overdueAmount+=capvo.getOverdueAmount();
				}
			}
			clearAmt=overplusCapAmt+overplusIntrAmt+overplusdefaultAmt+overdueAmount;
			mbm.setTotCapAmt(totCapAmt);
			mbm.setTotIntrAmt(totIntrAmt);
			mbm.setTotdefaultAmt(totdefaultAmt);//已还罚息合计
			mbm.setOverplusCapAmt(overplusCapAmt);
			mbm.setOverplusIntrAmt(overplusIntrAmt);
			mbm.setOverplusdefaultAmt(overplusdefaultAmt);
			mbm.setOverdueAmount(overdueAmount);
			mbm.setClearAmt(clearAmt);
		}
		return mcrbills;
	}

	@Override
	public List<InsApplicationVO> getInsPayInfo(Long cstId) throws BaseException {
		
		// TODO 自动生成的方法存根
		InsApplicationQC insqc=new InsApplicationQC();
		//insqc.setPerId(Long.parseLong("180420165010500"));
		CstBscInfoVO cstvo=cstBscInfoService.selectById(cstId);
		if(cstvo==null||null==cstvo.getUsrId()||"".equals(cstvo.getUsrId())){
			return null;
		}
		insqc.setPerId(cstvo.getUsrId());
		insqc.setLoanState("2");//已放款状态
		//查询保单申请信息
		List<InsApplicationDTO> insapps=insQueryApiService.searchInsPolicyList(insqc);

		List<Long> payIds = new ArrayList<Long>();
		if(CollectionUtils.isNotEmpty(insapps)){
			for(InsApplicationDTO dto:insapps){
				payIds.add(dto.getPaySchId());
			}
			
		}
		if(payIds.size()==0){
			return null;
		}
		//查询支付表信息
		//InsPayInfoQC insPayqc=new InsPayInfoQC();
		//insPayqc.setIdList(payIds);
		//查询支付表信息
		//List<InsPayInfoDTO> dtos=insQueryApiService.searchInsPayInfoList(insPayqc);
		//查询支付表信息02租金
		InsPayDetailIns02QC insPay02qc=new InsPayDetailIns02QC();
		insPay02qc.setInsPayInfoIdList(payIds);
		List<InsPayDetailIns02DTO>  detailIns02DTOs=insQueryApiService.searchInsPayDetailIns02List(insPay02qc);
		//查询支付表信息03本金
		InsPayDetailIns03QC insPay03qc=new InsPayDetailIns03QC();
		insPay03qc.setInsPayInfoIdList(payIds);
		List<InsPayDetailIns03DTO>  detailIns03DTOs=insQueryApiService.searchPayDet03List(insPay03qc);
		//查询支付表信息04利息
		InsPayDetailIns04QC insPay04qc=new InsPayDetailIns04QC();
		insPay04qc.setInsPayInfoIdList(payIds);
		List<InsPayDetailIns04DTO>  detailIns04DTOs=insQueryApiService.searchPayDet04List(insPay04qc);
		List<InsApplicationVO> insappvo=InsApplicationVOTransform.toVOList(insapps);
		//查询逾期数据
		CapOverdueInfoQueryCondition capcon=new CapOverdueInfoQueryCondition();
		capcon.setPaySchIdList(payIds);
		capcon.setCstId(cstId);
		capcon.setUsrId(CurrentThreadContext.getCurrentUserId());
		capcon.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		capcon.setSysCd(CurrentThreadContext.getCurrentSysCd());
		capcon.setDataStatusCd(BaseConstant.IS_YESNO_NO_STR);
//		List<CapOverdueInfoVO> capOverdues=capOverdueInfoService.searchOvdPayList(capcon);
		List<CapOverdueInfoVO> capOverdues=capOverdueInfoService.searchList(capcon);
		for(InsApplicationVO applicationVo:insappvo){
			Long totCapAmt=0L;//已还本金合计
			Long totIntrAmt=0L;//已还利息合计
			Long totdefaultAmt=0L;//已还罚息合计
			Long overplusCapAmt=0L; //剩余本金合计
			Long overplusIntrAmt=0L;//剩余利息合计
			Long overplusdefaultAmt=0L;//剩余罚息合计
			Long overdueAmount=0L;//逾期金额:逾期租金总金额
			Long clearAmt=0L;//结清--剩余本金合计+剩余利息合计+应收罚息合计+逾期租金合计
			for(InsPayDetailIns02DTO insPayInfo02DTO:detailIns02DTOs){
				if(applicationVo.getPaySchId().equals(insPayInfo02DTO.getInsPayInfoId())){
					
				}
			}
			for(InsPayDetailIns03DTO insPayInfo03DTO:detailIns03DTOs){
				if(applicationVo.getPaySchId().equals(insPayInfo03DTO.getInsPayInfoId())){
					totCapAmt+=insPayInfo03DTO.getPaidUpAmt();//已还本金合计
                    // 计算未来本金
                    if (insPayInfo03DTO.getRepaymentDt().after(new Date())) {
                        overplusCapAmt += insPayInfo03DTO.getArAmt();//剩余本金合计
                    }
				}
			}
			for(InsPayDetailIns04DTO insPayInfo04DTO:detailIns04DTOs){
				if(applicationVo.getPaySchId().equals(insPayInfo04DTO.getInsPayInfoId())){
					totIntrAmt+=insPayInfo04DTO.getPaidUpAmt();//已还本金合计
                    // 计算未来利息
                    if (insPayInfo04DTO.getRepaymentDt().after(new Date())) {
                        overplusIntrAmt += insPayInfo04DTO.getArAmt();//剩余利息合计
                    }
				}
			}
			for (CapOverdueInfoVO capvo : capOverdues) {
				if(applicationVo.getPaySchId().equals(capvo.getPaySchId())){
					totdefaultAmt+=capvo.getPayAmount();//payAmount
					overplusdefaultAmt+=(capvo.getPenaltyAmount()-capvo.getPayAmount());
					overdueAmount+=capvo.getOverdueAmount();
				}
			}
			clearAmt=overplusCapAmt+overplusIntrAmt+overplusdefaultAmt+overdueAmount;
			applicationVo.setTotCapAmt(totCapAmt);
			applicationVo.setTotCapAmt(totCapAmt);
			applicationVo.setTotIntrAmt(totIntrAmt);
			applicationVo.setTotdefaultAmt(totdefaultAmt);//已还罚息合计
			applicationVo.setOverplusCapAmt(overplusCapAmt);
			applicationVo.setOverplusIntrAmt(overplusIntrAmt);
			applicationVo.setOverplusdefaultAmt(overplusdefaultAmt);
			applicationVo.setOverdueAmount(overdueAmount);
			applicationVo.setClearAmt(clearAmt);
		}
	
		return insappvo;
	}

	@Override
	public void saveOrupdateflowInfo(ArrayList<McrBillMVO> billMVOs, ArrayList<InsApplicationVO> mcrbillinss,
			ArrayList<McrBillMVO> mcrbilllngs,String busid,String procId,String taskid) {
		// TODO 自动生成的方法存根
		AssTrailCarFlowHistoryQC qc=new AssTrailCarFlowHistoryQC();
		qc.setBusinessid(busid);
		qc.setProcessinstanceid(procId);
		qc.setTaskdefkey(taskid);
		List<AssTrailCarFlowHistoryDTO> dtos=assTrailCarFlowHistoryApi.searchAssTcFList(qc);
		List<Long> ids=new ArrayList<Long>();
		for(AssTrailCarFlowHistoryDTO dto:dtos){
			ids.add(dto.getId());
		}
		if(null!=dtos||dtos.size()>0){
			assTrailCarFlowHistoryApi.batchDelete(ids);
		}
		dtos=new ArrayList<AssTrailCarFlowHistoryDTO>();
		for(McrBillMVO vo:billMVOs){
			AssTrailCarFlowHistoryDTO dto=new AssTrailCarFlowHistoryDTO();
			dto.setContNo(vo.getCrCntNo());//CONT_NO
			dto.setCrTypCd(vo.getCrTypCd());//CR_TYP_CD
			dto.setActLoanAmt(vo.getActCrAmt());//ACT_LOAN_AMT
			dto.setRetOfCapital(vo.getTotCapAmt());//RET_OF_CAPITAL
			dto.setRetOfInteres(vo.getTotIntrAmt());//RET_OF_INTERES
			dto.setTotOfFine(vo.getTotdefaultAmt());//TOT_OF_FINE
			dto.setResidualPrincipal(vo.getOverplusCapAmt());//RESIDUAL_PRINCIPAL
			dto.setSurplusInterest(vo.getOverplusIntrAmt());//SURPLUS_INTEREST
			dto.setFineTot(vo.getOverplusdefaultAmt());//FINE_TOT
			dto.setOverdueRent(vo.getOverdueAmount());//OVERDUE_RENT
			dto.setReceivables(vo.getClearAmt());//RECEIVABLES
			//dto.setTotal();//TOTAL
			//dto.setCstId(vo.getCstId());//CST_ID
			dto.setBusinessid(busid);//BUSINESSID
			dto.setProcessinstanceid(procId);//PROCESSINSTANCEID
			dto.setTaskdefkey(taskid);//TASKDEFKEY
			dto.setCrtTm(vo.getCrtTm());//创建时间
			dto.setCrtUsrId(vo.getCrtUsrId());//创建人
			dto.setMdfTm(vo.getMdfTm());//修改时间
			dto.setMdfUsrId(vo.getMdfUsrId());//修改人
			dtos.add(dto);
		}
		for(InsApplicationVO vo:mcrbillinss){
			AssTrailCarFlowHistoryDTO dto=new AssTrailCarFlowHistoryDTO();
			dto.setContNo(vo.getContNo());//CONT_NO
			dto.setCrTypCd(vo.getLoanType());//CR_TYP_CD
			dto.setActLoanAmt(vo.getInsTotalAmt());//ACT_LOAN_AMT
			dto.setRetOfCapital(vo.getTotCapAmt());//RET_OF_CAPITAL
			dto.setRetOfInteres(vo.getTotIntrAmt());//RET_OF_INTERES
			dto.setTotOfFine(vo.getTotdefaultAmt());//TOT_OF_FINE
			dto.setResidualPrincipal(vo.getOverplusCapAmt());//RESIDUAL_PRINCIPAL
			dto.setSurplusInterest(vo.getOverplusIntrAmt());//SURPLUS_INTEREST
			dto.setFineTot(vo.getOverplusdefaultAmt());//FINE_TOT
			dto.setOverdueRent(vo.getOverdueAmount());//OVERDUE_RENT
			dto.setReceivables(vo.getClearAmt());//RECEIVABLES
			//dto.setTotal();//TOTAL
			//dto.setCstId(vo.getCstId());//CST_ID
			dto.setBusinessid(busid);//BUSINESSID
			dto.setProcessinstanceid(procId);//PROCESSINSTANCEID
			dto.setTaskdefkey(taskid);//TASKDEFKEY
			dto.setCrtTm(vo.getCrtTm());//创建时间
			dto.setCrtUsrId(vo.getCrtUsrId());//创建人
			dto.setMdfTm(vo.getMdfTm());//修改时间
			dto.setMdfUsrId(vo.getMdfUsrId());//修改人
			dtos.add(dto);
		}
		
		for(McrBillMVO vo:mcrbilllngs){
			AssTrailCarFlowHistoryDTO dto=new AssTrailCarFlowHistoryDTO();
			dto.setContNo(vo.getCrCntNo());//CONT_NO
			dto.setCrTypCd(vo.getCrTypCd());//CR_TYP_CD
			dto.setActLoanAmt(vo.getActCrAmt());//ACT_LOAN_AMT
			dto.setRetOfCapital(vo.getTotCapAmt());//RET_OF_CAPITAL
			dto.setRetOfInteres(vo.getTotIntrAmt());//RET_OF_INTERES
			dto.setTotOfFine(vo.getTotdefaultAmt());//TOT_OF_FINE
			dto.setResidualPrincipal(vo.getOverplusCapAmt());//RESIDUAL_PRINCIPAL
			dto.setSurplusInterest(vo.getOverplusIntrAmt());//SURPLUS_INTEREST
			dto.setFineTot(vo.getOverplusdefaultAmt());//FINE_TOT
			dto.setOverdueRent(vo.getOverdueAmount());//OVERDUE_RENT
			dto.setReceivables(vo.getClearAmt());//RECEIVABLES
			//dto.setTotal();//TOTAL
			//dto.setCstId(vo.getCstId());//CST_ID
			dto.setBusinessid(busid);//BUSINESSID
			dto.setProcessinstanceid(procId);//PROCESSINSTANCEID
			dto.setTaskdefkey(taskid);//TASKDEFKEY
			dto.setCrtTm(vo.getCrtTm());//创建时间
			dto.setCrtUsrId(vo.getCrtUsrId());//创建人
			dto.setMdfTm(vo.getMdfTm());//修改时间
			dto.setMdfUsrId(vo.getMdfUsrId());//修改人
			dtos.add(dto);
		}
		
		assTrailCarFlowHistoryApi.batchInsert(dtos);
		

		
	}

	@Override
	public Long getAllMoney(String tcMasterId) {
		// TODO 自动生成的方法存根
		if (StringUtils.isEmpty(tcMasterId)) {
			return 0L;
		}
		List<Long> ids = new ArrayList<Long>();
		AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
		qc.setMasterId(Long.valueOf(tcMasterId));
		qc.setIsDel(BaseConstant.IS_YESNO_NO);
		qc.setIsHis(BaseConstant.IS_YESNO_NO);
		List<AssTrailCarDVO> voList = this.assTrailCarDService.searchDetailList(qc);
		// 获取拖车详细信息IdList
		if (CollectionUtils.isNotEmpty(voList)) {
			for (AssTrailCarDVO vo : voList) {
				ids.add(vo.getId());
			}
		}

		List<AssTrailCarDVO> assTcvos = this.assTrailCarDService.selectByDetailId(ids);
		AssTrailCarDVO assTcvo = new AssTrailCarDVO();
		if (null != assTcvos && assTcvos.size() > 0) {
			assTcvo = assTcvos.get(0);
		}

		Long tcInfoId = assTcvo.getInfoId();
		Long paySchId = assTcvo.getPaySchId();
		AssTrailCarDInfVO vo = this.assTrailCarDInfService.selectById(tcInfoId);
		if (null == vo.getFutureAmt()) {

			List<Long> paySchids = new ArrayList<Long>();
			if (StringUtils.isEmpty(paySchId)) {
				return vo.getBaseAmt();
			} else {
				paySchids.add(Long.valueOf(paySchId));
			}
			List<AssTrailCarDInfVO> cardinfovos = this.assTrailCarDInfService.selectMoneyByPaySchId(paySchids);
			AssTrailCarDInfVO cardinfovo = new AssTrailCarDInfVO();
			if (null != cardinfovos && cardinfovos.size() > 0) {
				cardinfovo = cardinfovos.get(0);
			}
			Long overRentAmt = cardinfovo.getOverRentAmt() == null ? 0L : cardinfovo.getOverRentAmt();
			Long futureAmt = cardinfovo.getFutureAmt() == null ? 0L : cardinfovo.getFutureAmt();
			Long actPayAmt = cardinfovo.getActPayAmt() == null ? 0L : cardinfovo.getActPayAmt();
			Long otherAmt = cardinfovo.getOtherAmt() == null ? 0L : cardinfovo.getOtherAmt();
			Long performanceAmt = cardinfovo.getPerformanceAmt() == null ? 0L : cardinfovo.getPerformanceAmt();
			Long insureAmt = cardinfovo.getInsureAmt() == null ? 0L : cardinfovo.getInsureAmt();
			Long riskAmt = cardinfovo.getRiskAmt() == null ? 0L : cardinfovo.getRiskAmt();
			Long baseAmt = (overRentAmt + futureAmt + actPayAmt + otherAmt) - performanceAmt - insureAmt - riskAmt;
			vo.setBaseAmt(baseAmt);// 设置保底价格
		}
		Long cstId = assTcvo.getCstId();
		// 保险数据
		List<InsApplicationVO> insappvo = this.getInsPayInfo(cstId);
		List<McrBillMVO> mcrbills = this.getMcrBillInfo(cstId, null);
		Long baseAllAmt = vo.getBaseAmt();
		if(insappvo!=null){
			for (InsApplicationVO insvo : insappvo) {
				baseAllAmt += insvo.getClearAmt();
			}
		}
		if(mcrbills!=null){
			for (McrBillMVO loanvo : mcrbills) {
				baseAllAmt += loanvo.getClearAmt();
			}
		}
		return baseAllAmt;

	}
	


	
}
